const { ccclass, property } = cc._decorator;
import { gameEvents } from "../../constants";
import { IconResourcePath } from "../bean/Config";

//背包物品
@ccclass
export default class bagItem extends cc.Component {
    private selectedNode: cc.Node = null; //选中背景框
    private itemSprite: cc.Sprite = null; //物品图片
    private countLabel: cc.Label = null; //数量

    public itemId: string = null; //物品ID
    public itemCount: number = 0; //物品数量
    public remark: string = ""; //物品描述
    public itype: number = 1;
    public isSelected: boolean = false; //是否被选中

    onLoad() {
        this.selectedNode = this.node.getChildByName("selected");
        this.itemSprite = this.node.getComponent(cc.Sprite);
        this.countLabel = this.node.getChildByName("count").getComponent(cc.Label);

        this.onEvents();
    }

    start() {
        this.selectedNode.active = false;
    }

    protected onDestroy() {
        this.offEvents();
    }

    private onEvents() {
        this.node.on(cc.Node.EventType.TOUCH_END, this.onClick, this);
    }

    private offEvents() {
        this.node.off(cc.Node.EventType.TOUCH_END, this.onClick, this);
    }

    //初始化数据
    public init(itemId: string, count: number, remark: string, itype: number) {
        //当前背包的UI处于active时进行addChild并不会实时初始化该脚本的onLoad，所以这里判断一下
        if (this.countLabel == null) {
            this.countLabel = this.node.getChildByName("count").getComponent(cc.Label);
        }
        if (this.itemSprite == null) {
            this.itemSprite = this.node.getComponent(cc.Sprite);
        }

        this.itype = itype;
        this.itemId = itemId;
        this.remark = remark;
        this.itemCount = this.itemCount + count;

        this.countLabel.string = this.itemCount + "";
        cc.resources.load(IconResourcePath.bagItem + itemId, cc.SpriteFrame, (err, obj: any) => {
            this.itemSprite.spriteFrame = obj;
        });
    }

    //物品点击事件
    private onClick() {
        cc.log("点击");
        //清除其它选中
        for (let i = 0; i < this.node.parent.children.length; i++) {
            if (this.node.parent.children[i].getComponent("bagItem").isSelected == true) {
                this.node.parent.children[i].getChildByName("selected").active = false;
                this.node.parent.children[i].getComponent("bagItem").isSelected = false;
                break;
            }
        }
        this.selectedNode.active = true;
        this.isSelected = true;

        cc.director.emit(gameEvents.onBagItemClick.toString(), this.node);
    }

    //叠加物品数量
    public addItemCount(num: number) {
        this.itemCount = this.itemCount + num;
        this.countLabel.string = this.itemCount + "";
    }
}
